//
//  RDDataBase.swift
//  test-ios
//
//  Created by wyz5204 on 2023/6/5.
//

import Foundation
import GRDB
typealias DBColumn = GRDB.Column

struct RDDatabase {
    
    static func createPool(_ path : String) throws -> DatabasePool {
        var configuration = Configuration()
        configuration.qos = .userInitiated
        let pool = try DatabasePool(path: path, configuration: configuration)
        try pool.write { database in
            try database.execute(sql: "PRAGMA auto_vacuum = FULL")
        }
        return pool
    }
    
    static func recreate(_ path : String) throws -> DatabasePool  {
        try FileManager.default.removeItem(atPath: path)
        return try createPool(path)
    }
    
    static func migrateIfNeeded(_ dbPool : DatabasePool) throws {
        var migrator = GRDB.DatabaseMigrator()

        // v1 OrgBean 表的创建
        migrator.registerMigration("Create OrgBean table") { db in
            try db.create(table: OrgBean.databaseTableName, body: { table in
                table.column(OrgBean._id.name, .integer).primaryKey()
                table.column(OrgBean.owner.name, .text)
                table.column(OrgBean.orgName.name, .text)
                table.column(OrgBean.id.name, .integer)
                table.column(OrgBean.orgCode.name, .integer)
            })
        }
        
        // v2 Session 表的创建
        migrator.registerMigration("Create ChatSession table") { db in
            try db.create(table: ChatSession.databaseTableName, body: { table in
                table.column(ChatSession._id.name, .integer).primaryKey()
                table.column(ChatSession.id.name, .text)
                table.column(ChatSession.sessionID.name, .text)
                table.column(ChatSession.type.name, .integer)
                table.column(ChatSession.image.name, .text)
                table.column(ChatSession.name.name, .text)
                table.column(ChatSession.top.name, .boolean).defaults(to: false)
                table.column(ChatSession.from.name, .text)
                table.column(ChatSession.to.name, .text)
                table.column(ChatSession.unreadNum.name, .integer)
                table.column(ChatSession.lastModifyTime.name, .integer)
                table.column(ChatSession.updateTime.name, .integer)
                table.column(ChatSession.lastMessageText.name, .text)
                table.column(ChatSession.delFlag.name, .boolean).defaults(to: false)
                table.column(ChatSession.show.name, .boolean).defaults(to: true)
                table.column(ChatSession.lastMessageSeqID.name, .text)
                table.column(ChatSession.lastMsgIncrement.name, .text)
                table.column(ChatSession.isReadLastMessage.name, .integer).defaults(to: 0)
                table.column(ChatSession.reportFlag.name, .text)
                
            })
        }
        
        // v3 Session 表的添加字段
//        migrator.registerMigration("ChatSession table add column") { db in
//            guard try db.columns(in: ChatSession.databaseTableName)
//                    .contains(where: {$0.name == ChatSession.sessionID.name}) == false else {
//                return
//            }
//            try db.alter(table: ChatSession.databaseTableName) { (t) in
//                t.add(column: ChatSession.sessionID.name, .text)
////                t.add(column: RuuviTagSQLite.isOwnerColumn.name, .boolean)
////                    .notNull()
////                    .defaults(to: true)
//            }
//        }
        
        // v4 Session 表的字段更新名字
//        migrator.registerMigration("ChatSession table delete column") { db in
//            guard try db.columns(in: ChatSession.databaseTableName)
//                    .contains(where: {$0.name == ChatSession.sessionID.name}) == true else {
//                return
//            }
//            try db.alter(table: ChatSession.databaseTableName) { (t) in
//                t.rename(column:  ChatSession.sessionID.name, to: "session_id")
//            }
//        }
//
//        // v3
//        migrator.registerMigration("Create SensorSettingsSQLite table") { db in
////            guard try db.tableExists(SensorSettingsSQLite.databaseTableName) == false else { return }
////            try SensorSettingsSQLite.createTable(in: db)
////
////            guard try db.columns(in: RuuviTagDataSQLite.databaseTableName)
////                    .contains(where: {$0.name == RuuviTagDataSQLite.temperatureOffsetColumn.name}) == false else {
////                return
////            }
////            try db.alter(table: RuuviTagDataSQLite.databaseTableName, body: { (t) in
////                t.add(column: RuuviTagDataSQLite.temperatureOffsetColumn.name, .double)
////                    .notNull().defaults(to: 0.0)
////                t.add(column: RuuviTagDataSQLite.humidityOffsetColumn.name, .double)
////                    .notNull().defaults(to: 0.0)
////                t.add(column: RuuviTagDataSQLite.pressureOffsetColumn.name, .double)
////                    .notNull().defaults(to: 0.0)
////            })
//        }
//
//        // v4
//        migrator.registerMigration("Create RuuviTagDataSQLite source column") { db in
////            guard try db.columns(in: RuuviTagDataSQLite.databaseTableName)
////                    .contains(where: {$0.name == RuuviTagDataSQLite.sourceColumn.name}) == false else {
////                return
////            }
////            try db.alter(table: RuuviTagDataSQLite.databaseTableName, body: { (t) in
////                t.add(column: RuuviTagDataSQLite.sourceColumn.name, .text)
////                    .notNull().defaults(to: "unknown")
////            })
//        }
//
//        // v5
//        migrator.registerMigration("Create RuuviTagDataSQLite luid column") { db in
////            guard try db.columns(in: RuuviTagDataSQLite.databaseTableName)
////                    .contains(where: {$0.name == RuuviTagDataSQLite.luidColumn.name}) == false else {
////                return
////            }
////            try db.alter(table: RuuviTagDataSQLite.databaseTableName, body: { (t) in
////                t.add(column: RuuviTagDataSQLite.luidColumn.name, .text)
////            })
//        }
//        // v6
//        migrator.registerMigration("Create RuuviTagSQLite isCloudSensor column") { db in
////            guard try db.columns(in: RuuviTagSQLite.databaseTableName)
////                    .contains(where: {$0.name == RuuviTagSQLite.isCloudSensor.name}) == false else {
////                return
////            }
////            try db.alter(table: RuuviTagSQLite.databaseTableName, body: { (t) in
////                t.add(column: RuuviTagSQLite.isCloudSensor.name, .boolean)
////            })
//        }
//        // v7
//        migrator.registerMigration("Create RuuviTagSQLite firmwareVersion column") { db in
////            guard try db.columns(in: RuuviTagSQLite.databaseTableName)
////                    .contains(where: {$0.name == RuuviTagSQLite.firmwareVersionColumn.name}) == false else {
////                return
////            }
////            try db.alter(table: RuuviTagSQLite.databaseTableName, body: { (t) in
////                t.add(column: RuuviTagSQLite.firmwareVersionColumn.name, .text)
////            })
//        }
//        // v8
//        migrator.registerMigration("Create RuuviTagLatestDataSQLite table") { db in
////            try RuuviTagLatestDataSQLite.createTable(in: db)
//        }
//        // v8
//        migrator.registerMigration("Create RuuviCloudRequestQueueSQLite table") { db in
////            try RuuviCloudQueuedRequestSQLite.createTable(in: db)
//        }
//        // v9
//        migrator.registerMigration("Create RuuviTagSQLite canShare column") { db in
////            guard try db.columns(in: RuuviTagSQLite.databaseTableName)
////                    .contains(
////                        where: { $0.name == RuuviTagSQLite.canShareColumn.name}
////                    ) == false else {
////                return
////            }
////            try db.alter(table: RuuviTagSQLite.databaseTableName, body: { (t) in
////                t.add(
////                    column: RuuviTagSQLite.canShareColumn.name, .boolean
////                ).defaults(to: false)
////            })
//        }
//        // v10
//        migrator.registerMigration("Create RuuviTagSQLite sharedTo column") { db in
////            guard try db.columns(in: RuuviTagSQLite.databaseTableName)
////                    .contains(
////                        where: { $0.name == RuuviTagSQLite.sharedToColumn.name}
////                    ) == false else {
////                return
////            }
////            try db.alter(table: RuuviTagSQLite.databaseTableName, body: { (t) in
////                t.add(column: RuuviTagSQLite.sharedToColumn.name, .text)
////                    .defaults(to: "")
////            })
//        }

        try migrator.migrate(dbPool)
    }
}
